/**
 * 断开
 * 重连
 */
const WS_ADDRESS = 'ws://172.16.106.63:8080/websocket/'
const userIndexd = 'user-4'
function useWebSocket(handleMessage, handleCloseFun) {

  const ws = new WebSocket(WS_ADDRESS + userIndexd )

  let ModeCode = {
    MSG: 'message',//普通消息
    HEART_BEAT: 'heart_beat' //心跳检测消息
  }
  let webSocketState = false;//WebSocket连接状态
  let heartBeat = {
    time: 8 * 1000, //心跳检测间隔时间
    timeout: 8 * 1000, //心跳超时间隔
    reconnect: 10 * 1000  //断线重连时间
  }
  let reconnectTimer = null // 断线重连时间器

  const init = ()=>{
    bindEvent()
  }
  function bindEvent() {
    ws.addEventListener('open',handleOpen,false); // 成功回调
    ws.addEventListener('close',handleClose,false); // 关闭回调 
    ws.addEventListener('error',handleError,false); // 错误回调
    ws.addEventListener('message',handleMessage,false); // 接收信息
  }
  function handleOpen(e) {
    // ws状态 设置为连接: true
    webSocketState = true
    //是否启动心跳检测
    heartBeat && heartBeat.time ? startHeartBeat(heartBeat.time) : ''
    console.log('WebSocket open,开启',e)
  }

  function handleClose(e) {
    console.log('断开了666',e)
   
    handleCloseFun(e)
    // 重新连接
    reconnectWebSocket() 
  }

  function handleError(e) {
    webSocketState = false;
    startHeartBeat() // 重新连接
    console.log('连接发生了错误', e)
  }


  //心跳检测初始化函数
  function startHeartBeat(time){
    setTimeout(() => {
      // ws.send(
      //   // JSON.stringify({
      //   //   ModeCode: ModeCode.HEART_BEAT,
      //   //   msg: new Date()
      //   // })
      //   // JSON.stringify({})
      //   "HeartBeat"
      // )
      waitingServer();
    }, time);
  }
  //延时等待服务端响应，通过webSocketState判断是否连线成功
  function waitingServer(){
    webSocketState = false
    setTimeout(() => {
      if(webSocketState){
        startHeartBeat(heartBeat.time);
        return
      }
      console.log('心跳无响应,已经断线了')
      try {
        ws.close()
      } catch (e) {
        console.log('连接已关闭')
      }
      reconnectWebSocket()
    }, heartBeat.timeout);
  }
  //重新连接
  function reconnectWebSocket(){
    reconnectTimer = setTimeout(() => {
      reconnectWs();
    }, heartBeat.reconnect);
  }
  //控制执行
  function reconnectWs(){
    if (!ws) {// 第一次执行，初始化
      connectWebSocket()
    }
    if (ws && reconnectTimer) {   // 防止多个WebSocket同时执行
      clearInterval(reconnectTimer);
      ws.reconnectTimer = null
      reconnectWebSocket()
    }
  }

  init()
  return ws
}

export default useWebSocket